<script setup>
import {ref, onMounted, computed, watch} from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const statusList = ref([])
const activeStatus = ref('')
const orderList = ref([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const trackDialogVisible = ref(false)
const orderDetail = ref(null)

const getStatusList = async () => {
  try {
    const res = await axios.get('/carRepair/admin/repairOrderManage/status')
    if (res.data.code === 200) {
      statusList.value = res.data.data
      // 剔除"已预约""已派工"后，默认选中第一个状态
      const filtered = statusList.value.filter(s => s !== '已预约' && s !== '已派工')
      if (filtered.length > 0) {
        activeStatus.value = filtered[0]
      } else {
        activeStatus.value = ''
      }
    }
  } catch (e) {
    ElMessage.error('获取状态列表失败')
  }
}

const filteredStatusList = computed(() => statusList.value.filter(s => s !== '已预约' && s !== '已派工'))

const getOrderList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: page.value,
      pageSize: pageSize.value
    }
    if (activeStatus.value) {
      params.orderStatus = activeStatus.value
    }
    const res = await axios.get('/carRepair/admin/statisticalStatement/repairDispatchOrderPageList', { params })
    if (res.data.code === 200) {
      orderList.value = res.data.data.records
      total.value = res.data.data.total
    }
  } catch (e) {
    ElMessage.error('获取派工统计失败')
  } finally {
    loading.value = false
  }
}

const handleStatusSelect = (status) => {
  activeStatus.value = status
  page.value = 1
  getOrderList()
}

const showTrackDialog = async (row) => {
  try {
    const res = await axios.get(`/carRepair/admin/partManage/repairOrder/${row.repairId}`)
    if (res.data.code === 200) {
      orderDetail.value = res.data.data
      trackDialogVisible.value = true
    }
  } catch (e) {
    ElMessage.error('获取工单详情失败')
  }
}

const getFirstImage = (urls) => {
  if (!urls) return ''
  return urls.split(',')[0]
}
const getImageList = (urls) => {
  if (!urls) return []
  return urls.split(',')
}

onMounted(() => {
  getStatusList()
})

watch(activeStatus, () => {
  getOrderList()
})
</script>

<template>
  <div class="dispatch-order">
    <el-card>
      <!-- 状态选择菜单 -->
      <el-menu mode="horizontal" :default-active="activeStatus" @select="handleStatusSelect">
        <el-menu-item v-for="status in filteredStatusList" :key="status" :index="status">
          {{ status }}
        </el-menu-item>
      </el-menu>
      <!-- 派工统计表格 -->
      <el-table :data="orderList" style="width: 100%; margin-top: 20px" v-loading="loading">
        <el-table-column prop="assignmentId" label="派工记录ID" width="120" />
        <el-table-column prop="repairId" label="关联工单ID" width="120" />
        <el-table-column prop="employeeName" label="维修技师名字" width="120" />
        <el-table-column prop="customerName" label="客户名字" width="120" />
        <el-table-column prop="plateBrand" label="车辆品牌" width="100" />
        <el-table-column prop="plateNumber" label="车牌号" width="120" />
        <el-table-column prop="problemDesc" label="故障描述" />
        <el-table-column prop="assignTime" label="派工时间" width="180" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="showTrackDialog(scope.row)">工单跟踪</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="getOrderList"
          @current-change="getOrderList"
        />
      </div>
    </el-card>
    <!-- 工单跟踪弹窗 -->
    <el-dialog v-model="trackDialogVisible" title="工单详情及进度" width="600px">
      <div v-if="orderDetail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="故障拍照">
            <el-image v-if="orderDetail.problemImgUrls" style="width: 80px; height: 80px" :src="getFirstImage(orderDetail.problemImgUrls)" :preview-src-list="getImageList(orderDetail.problemImgUrls)" fit="cover" />
          </el-descriptions-item>
          <el-descriptions-item label="故障描述">{{ orderDetail.problemDesc }}</el-descriptions-item>
          <el-descriptions-item label="维修预算金额">¥{{ orderDetail.budgetAmount }}</el-descriptions-item>
          <el-descriptions-item label="实际结算金额">¥{{ orderDetail.actualCost }}</el-descriptions-item>
          <el-descriptions-item label="故障单创建时间">{{ orderDetail.createTime }}</el-descriptions-item>
          <el-descriptions-item label="客户回访记录">{{ orderDetail.feedback }}</el-descriptions-item>
        </el-descriptions>
        <el-divider>维修进度</el-divider>
        <el-collapse>
          <el-collapse-item v-for="trace in orderDetail.repairSchedule || []" :key="trace.traceId" :title="trace.orderStatus">
            <div>跟踪记录时间：{{ trace.traceDatetime }}</div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.dispatch-order {
  padding: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>